package com.biscuit.page.basicservice.bean;

import com.alibaba.fastjson.JSON;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * @author mazihao
 * @createTime 2024/4/18 15:24
 */
@Component
public class RedisCache {

    @Resource
    @Getter
    private RedissonClient redissonClient;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public void set2String(String key, String value, int timeout, TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value);
        redisTemplate.expire(key, timeout, timeUnit);
    }

    public void set2Json(String cacheKey, Object data, int expire, TimeUnit timeUnit) {
        this.set2String(cacheKey, JSON.toJSONString(data), expire, timeUnit);
    }

    public String get2String(String cacheKey) {
        Object obj = this.redisTemplate.opsForValue().get(cacheKey);
        if (Objects.nonNull(obj)) {
            return obj.toString();
        }
        return null;
    }

    public Integer get2Integer(String cacheKey) {
        Object obj = this.redisTemplate.opsForValue().get(cacheKey);
        return Integer.valueOf(
                Optional.ofNullable(obj).orElse(0).toString()
        );
    }

    public <T> T get2Json(String cacheKey, Class<T> clazz) {
        if (StringUtils.isBlank(cacheKey)) {
            return null;
        }
        Object obj = redisTemplate.opsForValue().get(cacheKey);
        if (Objects.nonNull(obj)) {
            return clazz.cast(obj);
        }
        return null;
    }

    /**
     * 存储字符串缓存
     */
    public void set(String cacheKey, String value, long time, TimeUnit timeUnit) {
        this.redisTemplate.opsForValue().set(cacheKey, value);
        this.expired(cacheKey, time, timeUnit);
    }

    public void set(String cacheKey, String value, long second) {
        this.redisTemplate.opsForValue().set(cacheKey, value);
        this.expired(cacheKey, second, TimeUnit.SECONDS);
    }

    public void expired(String cacheKey, long time, TimeUnit timeUnit) {
        long second = TimeUnit.SECONDS.convert(time, timeUnit);
        long breakdown = ThreadLocalRandom.current().nextLong(10, 30);
        this.redisTemplate.expire(cacheKey, second + breakdown, TimeUnit.SECONDS);
    }

    public void setObject(String cacheKey, Object obj, long second) {
        this.redisTemplate.opsForValue().set(cacheKey, obj);
        this.expired(cacheKey, second, TimeUnit.SECONDS);
    }

    public void setObject(String cacheKey, Object obj, long time, TimeUnit timeUnit) {
        this.redisTemplate.opsForValue().set(cacheKey, obj);
        long second = TimeUnit.SECONDS.convert(time, timeUnit);
        long breakdown = ThreadLocalRandom.current().nextLong(10, 30);
        this.redisTemplate.expire(cacheKey, second + breakdown, TimeUnit.SECONDS);
    }

    /**
     * 获取 key 的过期时间（秒）
     */
    public long getKeyExpired(String cacheKey) {
        if (StringUtils.isBlank(cacheKey)) {
            return 0L;
        }
        Long expire = this.redisTemplate.getExpire(cacheKey);
        return Optional.ofNullable(expire).orElse(0L);
    }

    /**
     * 删除指定 key
     */
    public void delete(String cacheKey) {
        this.redisTemplate.delete(cacheKey);
    }

    /**
     * 删除多个 key
     */
    public void delete(String...cacheKeys) {
        this.redisTemplate.delete(Arrays.asList(cacheKeys));
    }


    /**
     * 判断 key 是否存在
     *
     * @param key key
     * @return ture 存在，false 不存在
     */
    public boolean isKeyExists(String key) {
        if (StringUtils.isBlank(key)) {
            return Boolean.FALSE;
        }
        Boolean exists = this.redisTemplate.hasKey(key);
        return Objects.nonNull(exists) ? exists.booleanValue() : Boolean.FALSE;
    }

}
